package cn.gcjxsc.payment.controller;

import cn.gcjxsc.common.consts.OrderDiscr;
import cn.gcjxsc.common.consts.PayChannel;
import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.common.data.notify.order.ResultHandleData;
import cn.gcjxsc.common.util.PaymentResultUtil;
import cn.gcjxsc.payment.data.PaymentResultConfig;
import cn.gcjxsc.payment.data.WeChatConfig;
import cn.gcjxsc.payment.data.wx.xml.PayResult;
import cn.gcjxsc.payment.entity.wx.PayRecord;
import cn.gcjxsc.payment.service.wx.PayRecordService;
import cn.gcjxsc.payment.service.wx.PayResultService;
import com.zgxl.common.util.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 微信支付回调地址
 *
 * @author pumbaa
 * @since 1.0
 */
@RestController
@RequestMapping("/wx/api/payment")
public class PayResponseController {
    private Logger logger = LoggerFactory.getLogger(PayResponseController.class);
    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private PayResultService payResultService;
    @Autowired
    private PayRecordService payRecordService;
    @Autowired
    private PaymentResultConfig paymentResultConfig;

    /**
     * 微信支付回调.
     *
     * @param request
     */
    @RequestMapping("/receive")
    public void receive(HttpServletRequest request) {
        String xml = payResultService.getXmlFromRequest(request);
        if (null == xml) {
            return;
        }
        logger.info("回调结果:{}", xml);
        Map<String, String> params;
        try {
            params = XmlUtil.xmlToMap(xml);
        } catch (Exception e) {
            logger.error("xml转map出错.{}, {}", e.getMessage(), xml);
            return;
        }
        if (!payResultService.verifySign(params, weChatConfig)) {
            return;
        }
        PayResult payResult = XmlUtil.convertToObject(PayResult.class, xml);
        if (null == payResult) {
            logger.error("处理微信回调结果出错.{}", xml);
            return;
        }
        PayRecord payRecord = payRecordService.findByTradeNo(payResult.getOut_trade_no());
        if (null == payRecord) {
            logger.error("无效交易信息.{}", xml);
            return;
        }
        if (payRecord.getStatus() == PayStatus.UNPAY.ordinal()) {
            payResultService.processPayResult(payResult, payRecord);
            try {
                payRecord = payRecordService.saveOrUpdate(payRecord);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("处理数据出错.{}, {}", payRecord.getSn(), e.getMessage());
                return;
            }
        }
        logger.info("支付是否成功:{}", payResultService.isPaySuccess(payResult) ? 1 : 0);
        if (payResultService.isPaySuccess(payResult)) {
            ResultHandleData data = new ResultHandleData();
            data.setAmount(Long.valueOf(payResult.getTotal_fee()));
            data.setAttach(payResult.getAttach());
            data.setSn(payRecord.getSn());
            data.setOutTradeNo(payResult.getTransaction_id());
            data.setTradeNo(payResult.getOut_trade_no());
            data.setChannel(PayChannel.WECHAT.name());
            data.setDiscr(payRecord.getSnDiscr());

            String sign = PaymentResultUtil.md5(data, paymentResultConfig.getKey());
            data.setSign(sign);

            payResultService.handle(data);
        }
    }
}
